<template>
  <v-page
    v-model="refreshing"
    background="#f5f6fa"
    footer-background="white"
    :loading="loading"
    @tolower="getList"
  >
    <template #header>
      <v-navbar title="全部评价" background-color="transparent" color="black" />
    </template>
    <template #default>
      <view class="comment-header">
        <view class="comment-title">
          <view class="comment-title-before_rate">
            {{ `${splitApplauseRate.before}.` }}
          </view>
          <view class="comment-title-after_rate">
            {{ `${splitApplauseRate.after}%` }}
          </view>
          <view class="comment-title-text">
            好评率
          </view>
        </view>

        <wd-rate
          v-model="score"
          color="#E1D5D7"
          active-color="linear-gradient(161.57deg, #FF6F6F 28.44%, #FF2F3B 75.31%);"
          readonly
        />
      </view>

      <view class="comment-subtitle">
        {{ `全部(${commentSum})` }}
      </view>

      <view class="comment-list">
        <landing-page-comment-group-tag-list
          v-if="commentGroup"
          :active="activeTag"
          :tag-list="tagList"
          @click-tag="clickTagHandle"
        />

        <landing-page-comment-group-content
          v-for="comment in groupCommentList"
          :key="comment.id"
          :comment="comment"
          show-thumb
          show-reply
          show-comment-time
        />
      </view>

      <v-loadmore :state="state" @reload="getList" />
    </template>
    <template #footer>
      <view class="landing-page-footer">
        <view class="group-button buy-immediately" @click="showOrder">
          立即下单
        </view>
      </view>
    </template>
    <template #popup>
      <landing-page-select-popup
        v-if="product"
        v-model:show="isShowSelect"
        :product="product"
      />
    </template>
  </v-page>
</template>

<script setup lang="ts">
import LandingPageSelectPopup from './modules/landing-page-select-popup.vue';
import LandingPageCommentGroupTagList from './modules/landing-page-comment-group-tag-list.vue';
import LandingPageCommentGroupContent from './modules/landing-page-comment-group-content.vue';

const refreshing = ref(false);
const loading = ref(true);
const component = ref<LandingPageCommentGroupItem>({
  id: '',
  el: 'CommentGroup',
  controlPositiveRate: 'custom',
  commentGroupId: '',
  positiveRate: 0,
  showCommentSummary: false,
  commentSummary: ''
});

const landingStore = $store.landing();
const product = computed(() => landingStore.product);

const splitApplauseRate = computed(() => {
  let positiveRate = commentGroup.value?.positive_rate || 0;
  if (component.value.controlPositiveRate === 'custom') {
    positiveRate = component.value.positiveRate / 100;
  }
  const rate = positiveRate * 100;
  const [before = '0', after = '0'] = rate.toFixed(2).split('.');
  return { before, after };
});

const score = computed(() => {
  if (component.value.controlPositiveRate === 'custom') {
    return (component.value.positiveRate / 100) * 5;
  }
  return (commentGroup.value?.positive_rate || 0) * 5;
});

const tagList = computed(() => {
  const list: { id?: string; name: string; count: number }[] = [];
  (commentGroup.value?.group_comment_tags ?? []).forEach((tag) => {
    const num = parseInt(tag.cnt);
    if (!isNaN(num) && num) {
      const item = list.find((item) => item.name === tag.tag_name);
      if (item) {
        item.count += num;
      } else {
        list.push({ name: tag.tag_name, count: num });
      }
    }
  });
  return list;
});
const activeTag = ref<{ id?: string; name: string }>();
const clickTagHandle = (tag?: { id?: string; name: string }) => {
  initList();
  activeTag.value = tag;

  getList();
};

const commentGroup = ref<SpuCommentGroupAdLandingVO>();
const groupCommentList = ref<SpuCommentGroupCommentOrderVO[]>([]);
const commentSum = computed(() => {
  const total = commentGroup.value?.total ?? '0';
  return parseInt(total) > 9999 ? '1w+' : total;
});

const groupCommentPageIndex = ref(1);
const groupCommentState = ref<'loading' | 'finished' | 'error'>();
const getGroupCommentList = async () => {
  if (!product.value?.id) return;
  if (
    groupCommentState.value !== undefined &&
    groupCommentState.value !== 'error'
  ) {
    return;
  }
  groupCommentState.value = 'loading';
  const response = await $api.getProductSpuCommentGroupId(
    component.value.commentGroupId,
    {
      page_no: groupCommentPageIndex.value,
      tag_name: activeTag.value && activeTag.value.name,
      page_size: 10
    }
  );

  switch (response.__error) {
    case undefined:
      commentGroup.value = response.data;

      groupCommentList.value.push(
        ...(response.data?.comment_group_comment_order_list ?? [])
      );
      groupCommentPageIndex.value++;

      if (groupCommentList.value.length >= parseInt(response.data.total)) {
        groupCommentState.value = 'finished';
      } else {
        groupCommentState.value = undefined;
      }
      break;
    default:
      groupCommentState.value = 'error';
  }
};

const state = computed(() => {
  if (groupCommentState.value === 'error') return 'error';
  if (groupCommentState.value === 'loading') return 'loading';
  if (groupCommentState.value === 'finished') {
    return 'finished';
  }
  return undefined;
});

const initList = () => {
  activeTag.value = undefined;
  groupCommentList.value = [];
  groupCommentPageIndex.value = 1;
  groupCommentState.value = undefined;
};

const getList = async () => {
  await getGroupCommentList();
};

onLoad(async () => {
  loading.value = true;
  const pageStore = $store.page();
  component.value = pageStore.parameters as LandingPageCommentGroupItem;
  await getList();
  loading.value = false;
});

const isShowSelect = ref(false);
const showOrder = () => {
  isShowSelect.value = true;
};
</script>

<style lang="scss" scoped>
.comment-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100rpx;
  background: linear-gradient(
    180deg,
    rgba(255, 47, 59, 0.1) 0%,
    rgba(255, 255, 255, 0.1) 100%
  );
  padding: 0 32rpx;

  .comment-title {
    display: flex;
    align-content: center;

    .comment-title-before_rate {
      font-weight: 700;
      font-size: 40rpx;
      color: #ff2f3b;
      line-height: 24rpx;
    }
    .comment-title-after_rate {
      font-weight: 700;
      font-size: 28rpx;
      color: #ff2f3b;
    }
    .comment-title-text {
      margin-left: 12rpx;
      font-weight: 400;
      font-size: 28rpx;
      color: #ff2f3b;
    }
  }
}

.comment-subtitle {
  font-weight: 800;
  font-size: 28rpx;
  line-height: 70rpx;
  color: #333333;
  padding: 0 24rpx;
}

.comment-list {
  position: relative;
  padding: 0 24rpx;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  gap: 20rpx;
}

.landing-page {
  background-color: white;
  border-radius: 16rpx 16rpx 0 0;
  .landing-page-header {
    line-height: 93rpx;
    padding: 0 48rpx;
    font-weight: bold;
    font-size: 32rpx;
  }
}

.landing-page-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24rpx;
  height: 100rpx;

  .group-button {
    width: 100%;
    line-height: 80rpx;
    text-align: center;
    font-size: 28rpx;
    font-weight: bold;
  }
  .buy-immediately {
    color: white;
    background-color: #ff2f3b;
    border-radius: 40rpx;
  }
}
</style>
